package 刷题.leedcode11;

import java.util.Stack;

//利用栈
public class Partition2 {
    public ListNode partition(ListNode pHead,int x){
        //创建一个栈，将所有小于x得值存放在栈中
        //将栈中元素一一取出，并采用头茬重新插入链表中
        if(pHead == null){
            return pHead;
        }
        Stack<Integer> stack = new Stack<>();
        //创建两个工具结点
        ListNode prev = null;
        ListNode cur = pHead;
        while(cur != null){
            if(cur.val < x){
                stack.add(cur.val);
                if(cur == pHead){
                    pHead = pHead.next;
                    cur = pHead;
                }else{
                    cur = cur.next;
                    prev.next = cur;
                }
            }else{
                prev = cur;
                cur = cur.next;
            }
        }
        while(!stack.isEmpty()){
            //头插
            ListNode newNode = new ListNode(stack.pop());
            newNode.next = pHead;
            pHead = newNode;
        }
        return pHead;
    }
}
